package com.proxy.server.frontend.handler.request.proxy;

import com.proxy.common.constant.FieldsType;
import com.proxy.common.model.Table;
import com.proxy.common.packet.*;
import com.proxy.common.utils.PacketUtil;
import com.proxy.router.SQLRouteResult;
import com.proxy.server.context.AppContext;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.session.Session;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.nio.charset.Charset;

/**
 * Created by liufish on 16/7/25.
 */
public class ShowTablesProxy {


    public static void doProxy(BinaryPacket bin, Session session, SQLRouteResult result) {

        FrontendConnection connection = session.getFrontendConnection();

        int FIELD_COUNT = 2;

        Channel channel = connection.getChannel();
        ByteBuf buffer = channel.alloc().buffer();

        // write header
        ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
        header.packetId = ++bin.packetId;
        buffer = header.writeBuffer(buffer);

        // write fields
        FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
        for (FieldPacket field : fields) {
            field = PacketUtil.getField("TABLE", FieldsType.FIELD_TYPE_VAR_STRING);
            field.packetId = ++bin.packetId;
            buffer = field.writeBuffer(buffer);
        }

        // write eof
        EOFPacket eof = new EOFPacket();
        eof.packetId = ++bin.packetId;
        buffer = eof.writeBuffer(buffer);

        // write rows

        for (Table table : AppContext.getInstance().getFrontendProxy().getTables()) {
            RowDataPacket row = new RowDataPacket(FIELD_COUNT);
            byte[] names = table.getName().getBytes(Charset.forName(connection.getCharset()));
            row.add(names);
            byte[] info = "BASE TABLE".getBytes(Charset.forName(connection.getCharset()));
            row.add(info);
            row.packetId = ++bin.packetId;
            buffer = row.writeBuffer(buffer);
        }

        // write last eof
        EOFPacket lastEof = new EOFPacket();
        lastEof.packetId = ++bin.packetId;
        buffer = lastEof.writeBuffer(buffer);
        connection.write(buffer);


    }

}
